<template>
  <el-form :model="queryParams" ref="queryForm" size="default" :inline="true">
    <el-form-item label="用户账号" prop="userName">
      <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户账号"
          clearable
          style="width: 240px"
      />
    </el-form-item>
    <el-form-item label="手机号" prop="phonenumber">
      <el-input
          v-model="queryParams.userName"
          placeholder="请输入手机号"
          clearable
          style="width: 240px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-perms="['system:role:add']"
          v-preventReClick
      >新增
      </el-button>
    </el-col>
  </el-row>


  <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="tableData"
      row-key="menuId"
  >
    <el-table-column label="用户编号" align="center" key="userId" prop="userId"/>
    <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true"/>
    <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true"/>
    <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120"/>
    <el-table-column label="状态" align="center" key="status">
      <template #default="scope">
        <status-tag :status="scope.row.status"/>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" align="center" prop="createTime" width="260"/>
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template #default="scope">
        <template v-if="scope.row.userId !== 1">
          <el-tooltip placement="top" content="修改">
            <el-button
                link
                icon="Edit"
                type="primary"
                v-perms="['system:role:edit']"
                v-preventReClick
                @click="handleUpdate(scope.row)"/>
          </el-tooltip>
          <el-tooltip placement="top" content="删除">
            <el-button
                link
                icon="Delete"
                v-perms="['system:role:remove']"
                type="danger"
                v-preventReClick
                @click="handleDelete(scope.row)"/>
          </el-tooltip>
          <el-tooltip placement="top" content="重置密码">
            <el-button
                link
                icon="Key"
                v-perms="['system:role:edit']"
                type="primary"
                v-preventReClick
                @click="handleResetPwd(scope.row)"/>
          </el-tooltip>
        </template>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-if="total>0"
      v-model:current-page="queryParams.pageNum"
      :page-size="10"
      layout="total, prev, pager, next"
      :total="total"
      style="float: right"
  />

  <el-dialog :title="title" v-model="open" width="700px" append-to-body :before-close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户昵称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="form.email" placeholder="请输入邮箱"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="form.userId === undefined" label="用户名称" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.userId === undefined" label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入用户密码" type="password" show-password/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio value="0" size="large">正常</el-radio>
              <el-radio value="1" size="large">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="form.roleId" placeholder="请选择角色">
              <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel" v-preventReClick>取 消</el-button>
      <el-button type="primary" @click="submitForm" v-perms="['system:role:add','system:role:edit']" v-preventReClick>确
        定
      </el-button>
    </template>
  </el-dialog>
</template>
<script>
import StatusTag from "@/components/StatusTag.vue";
import {RoleService} from "@/api/system/role.js";
import {UserService} from "@/api/system/user.js";
import {md5} from "js-md5";

export default {
  name: "SystemRole",
  components: {StatusTag},
  data() {
    return {
      // 查询参数
      queryParams: {
        // 用户账号
        userName: '',
        // 手机号码
        phonenumber: ''
      },
      // 遮罩层
      loading: true,
      // 表格树数据
      tableData: [],
      // 重新渲染表格状态
      refreshTable: true,
      // 总共页码
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        status: '0'
      },
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"},
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"},
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\ |", trigger: "blur" }
        ],
        roleId:[
          {required: true, message: "角色不能为空", trigger: "blur"}
        ]
      },
      // 性别选项
      sexOptions: [
        {value: '0', label: '男'},
        {value: '1', label: '女'},
        {value: '2', label: '未知'}
      ],
      // 角色选项
      roleOptions: []
    }
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        roleIds: undefined
      };
      this.$refs.form.resetFields()
    },
    getAllRole(){
      RoleService.allRole().then(resp=>{
        this.roleOptions = resp.data;
      })
    },
    getList() {
      this.loading = true;
      UserService.getUserList(this.queryParams).then(resp => {
        this.tableData = resp.rows
        this.total = resp.total;
        this.loading = false;
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    handleAdd() {
      this.title = '添加用户'
      this.open = true;
      this.$nextTick(()=>{
        this.reset();
      })
    },
    cancel() {
      this.reset();
      this.open = false;
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.form.userId !== undefined) {
            const {code} = await UserService.updateUser(this.form);
            if (code === 200) {
              this.$message.success('修改成功');
              this.open = false;
              this.getList();
            }
          } else {
            let data = this.form;
            data.password = md5(data.password)
            const {code} = await UserService.addUser(data);
            if (code === 200) {
              this.$message.success('新增成功');
              this.open = false;
              this.getList();
            }
          }
        }
      })
    },
    handleUpdate(row) {
      const userId = row.userId;
      UserService.getUser(userId).then(resp => {
        this.form = resp.data;
        this.open = true;
        this.title = '修改角色'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let _ = this;
      const userId = row.userId;
      _.$confirm('是否确认删除角色编号为"' + userId + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        UserService.deleteUser(userId).then(resp => {
          if (resp.code === 200) {
            _.$message.success('删除成功');
            _.getList();
          }
        })
      }).catch(() => {
      });
    },
    handleResetPwd(row){
      this.$prompt(`请输入${row.userName}的新密码`,'提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        closeOnClickModal:false,
        inputPattern:/^.{5,20}$/,
        inputErrorMessage:'密码长度介于5和20之间',
        inputValidator:(value)=>{
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\ |"
          }
        },
      }).then(({value})=>{
        let formData = {
          userId:row.userId,
          password:md5(value)
        }
        UserService.resetUserPwd(formData).then(resp=>{
          if(resp.code === 200){
            this.$message.success(`修改成功，密码是:${value}`);
          }
        })
      }).catch(()=>{})
    }
  },
  created() {
    this.getList();
    this.getAllRole();
  }
}
</script>
<style scoped>
</style>
